package com.campus.merchant.listener;

import com.campus.common.message.NewOrderMessage;
import com.campus.merchant.service.WebSocketService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class KafkaConsumerListener {

    @Autowired
    private WebSocketService webSocketService;
    
    @Resource
    private ObjectMapper objectMapper;

    private static final String NEW_ORDER_TOPIC = "new-order-topic";

    @KafkaListener(topics = NEW_ORDER_TOPIC, groupId = "merchant-group")
    public void onNewOrderReceived(String messageJson) {
        try {
            log.info("接收到新订单消息: {}", messageJson);
            
            // 解析JSON消息
            NewOrderMessage message = objectMapper.readValue(messageJson, NewOrderMessage.class);

            // 构建通知消息内容
            String notification = "您有新的订单，请及时处理！订单ID: " + message.getOrderId();

            // 通过WebSocketService发送订单通知
            webSocketService.sendOrderNotification(message.getMerchantId(), notification);

            log.info("已将新订单通知推送至商户: {}", message.getMerchantId());
        } catch (Exception e) {
            log.error("处理新订单消息失败: {}", e.getMessage(), e);
        }
    }
}